package com.dupf.upms.rpc.service.impl;

import com.dupf.common.util.ItvJsonUtil;
import com.dupf.common.util.RedisUtil;
import com.dupf.upms.common.constant.UpmsConstant;
import com.dupf.upms.rpc.api.UpmsUploadService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class QiniuUploadServiceImpl implements UpmsUploadService {
    private static final Logger LOGGER = LoggerFactory.getLogger(QiniuUploadServiceImpl.class);

    private Auth qiniuAuth = Auth.create(UpmsConstant.QINIU_ACCESS_KEY, UpmsConstant.QINIU_SECRET_KEY);

    @Override
    public Map<String, Object> getQiniuToken(String uid, String bucket, String module) {
        String cacheToken = RedisUtil.get(UpmsConstant.UPLOAD_REDIS_PREFIX + "bucket:" + bucket);

        Map<String, Object> map = null;

        if (!StringUtils.isEmpty(cacheToken)) {
            map = ItvJsonUtil.readValue(cacheToken, new TypeReference<Map<String, Object>>() {
            });
            int applyTime = (int) map.get("applyTime");
            int expires = (int) map.get("expires");
            int restExpires = expires + applyTime - (int) (System.currentTimeMillis() / 1000);
            map.put("expires", restExpires);

            return map;
        }

        long expires = UpmsConstant.QINIU_TOKEN_EXPIRES;
        String uploadToken = qiniuAuth.uploadToken(bucket, null, expires, null);

        map = new HashMap<>();
        map.put("uploadToken", uploadToken);
        map.put("applyTime", System.currentTimeMillis() / 1000);
        map.put("expires", expires);

        if (UpmsConstant.QINIU_BUCKET_VIDEO.equals(bucket)) {
            String auxiliaryBucket = UpmsConstant.QINIU_BUCKET_PICTURE;
            String auxiliaryToken = qiniuAuth.uploadToken(auxiliaryBucket, null, expires, null);
            map.put("auxiliaryToken", auxiliaryToken);
        }

        RedisUtil.set(UpmsConstant.UPLOAD_REDIS_PREFIX + "bucket:" + bucket, ItvJsonUtil.writeValue(map), UpmsConstant.UPLOAD_REDIS_EXPIRE * 60);

        return map;
    }

    /**
     * 直接上传网络图片
     *
     * @param url
     * @param bucket
     * @return
     */
    @Override
    public Map<String, Object> uploadUrlFile(String url, String bucket) {
        Auth auth = Auth.create(UpmsConstant.QINIU_ACCESS_KEY, UpmsConstant.QINIU_SECRET_KEY);
        BucketManager bm = new BucketManager(auth, new Configuration());
        try {
            FetchRet fetchRet = bm.fetch(url, bucket);
            Map<String, Object> map = new HashMap<>();
            map.put("key", fetchRet.key);
            map.put("hash", fetchRet.hash);
            map.put("mimeType", fetchRet.mimeType);
            map.put("fsize", fetchRet.fsize);

            return map;
        } catch (QiniuException e) {
            LOGGER.error("上传网络图片到七牛云报错", e);
        }

        return null;
    }
}
